﻿using System;
using System.Collections.Generic;
using System.Linq;
using Best.SmartCms.Portal.Models;
using Best.SmartCms.Service;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;

namespace Best.SmartCms.Portal.Components
{
    [ViewComponent(Name = "Navigation")]
    public class NavigationViewComponent : ViewComponent
    {
        private readonly ChannelGroupService _channelGroupService;
        private readonly ChannelService _channelService;
        private readonly IMemoryCache _cache;

        public NavigationViewComponent(IMemoryCache memoryCache, ChannelGroupService channelGroupService, ChannelService channelService)
        {
            _channelGroupService = channelGroupService;
            _channelService = channelService;
            _cache = memoryCache;
        }

        public IViewComponentResult Invoke()
        {
            var siteMenus = _cache.Get<List<MenuViewModel>>("SiteMenu");
            if (siteMenus == null || siteMenus.Count < 1)
            {

                var groups = _channelGroupService.FindAll().Where(p => p.IsShow).Take(5).OrderBy(p => p.OrderNo)
                    .ToList();
                var channels = _channelService.FindAll().Where(p => p.IsShowMenu).OrderBy(p => p.OrderNo).ToList();
                siteMenus = new List<MenuViewModel>();
                foreach (var item in groups)
                {
                    var children = channels.Where(p => p.ChannelGroupId == item.Id).ToList();
                    siteMenus.Add(new MenuViewModel
                    {
                        Children = children.Select(p => new MenuItem {Id = p.Id, Name = p.Name,Url = p.ControllerName}).ToList(),
                        GroupName = item.Name
                    });
                }

                _cache.Set("SiteMenu", siteMenus,TimeSpan.FromHours(2));
            }

            return View(siteMenus);
        }
    }
}
